using System;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace FytSoa.Common.Utils
{
    public class AppConfigUtils
    {
        public static IServiceProvider ServiceProvider;
        public static IConfiguration Configuration;

        public static void InitConfig(IConfiguration _configuration)
        {
            Configuration = _configuration;
        }
        
        private static string _MySqlConnectionString = string.Empty;
        /// <summary>
        /// MySql默认连接串
        /// </summary>
        public static string MySqlConnectionString
        {
            get
            {
                if (string.IsNullOrEmpty(_MySqlConnectionString))
                {
                    _MySqlConnectionString = Configuration["SqlConnectionString:MySql"];
                }
                return _MySqlConnectionString;
            }
        }
        
        private static string _RedisConnectionString = string.Empty;
        /// <summary>
        /// Redis默认连接串
        /// </summary>
        public static string RedisConnectionString
        {
            get
            {
                if (string.IsNullOrEmpty(_RedisConnectionString))
                {
                    _RedisConnectionString = Configuration["Cache:Redis"];
                }
                return _RedisConnectionString;
            }
        }
    }
    
    public static class ServiceLocator
    {
        public static IServiceProvider Instance { get; set; }

        /// <summary>
        /// 手动获取注入的对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetService<T>() where T : class
        {
            var httpContext = Instance?.GetService<IHttpContextAccessor>()?.HttpContext;
            return httpContext?.RequestServices.GetService<T>();
        }
    }
    
}